import relationalStore from '@ohos.data.relationalStore'; // 导入模块
import { Contact } from '../model/Contact';

const STORE_CONFIG = {
  name: 'RdbTest.db', // 数据库文件名
  securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别
};

const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS CONTACT (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, PHONE TEXT NOT NULL)'; // 建表Sql语句

class ContactDataManager {

  // 数据库 RdbStore 实例
  private contactDataRdbStore: relationalStore.RdbStore;

  /**
   * 创建或启动数据库，返回数据库实例
   *
   * @param context 需传入EntryAbility上下文
   */
  createDataBase(context) {
    relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
      if (err) {
        console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info('Succeeded in getting RdbStore.');
      store.executeSql(SQL_CREATE_TABLE); // 创建数据表

      // 请确保获取到RdbStore实例后，再进行数据库的增、删、改、查等操作
      this.contactDataRdbStore = store;
    });
  }

  /**
   * 存储联系人信息
   *
   * @param name  姓名
   * @param phone 电话号码
   */
  saveNewContact(name: string, phone: string) {
    let valueBucket = {
      'NAME': name,
      'PHONE': phone
    }
    this.contactDataRdbStore.insert('CONTACT', valueBucket, (err, rowId) => {
      if (err) {
        console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info(`Succeeded in inserting data. rowId:${rowId}`);
    })
  }

  /**
   * 读取所有联系人信息
   *
   * @param callback 回调函数，函数需允许传入 1 个入参
   */
  readContacts(callback: Function) {
    let predicates = new relationalStore.RdbPredicates('CONTACT');
    this.contactDataRdbStore.query(predicates, ['ID', 'NAME', 'PHONE'], (err, resultSet) => {
      if (err) {
        console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
        return;
      }
      console.info(`ResultSet column names: ${resultSet.columnNames}`);
      console.info(`ResultSet column count: ${resultSet.columnCount}`);
      console.info(`ResultSet: ${JSON.stringify(resultSet)}}`);

      let count: number = resultSet.rowCount;
      resultSet.goToFirstRow();
      let result: Contact[] = [];
      for (let i = 0; i < count; i++) {
        let tmp: Contact = { id: 0, name: '', phone: '' };
        tmp.id = resultSet.getDouble(resultSet.getColumnIndex('ID'));
        tmp.name = resultSet.getString(resultSet.getColumnIndex('NAME'));
        tmp.phone = resultSet.getString(resultSet.getColumnIndex('PHONE'));
        result[i] = tmp;
        resultSet.goToNextRow();
      }
      resultSet.close();
      for (let i = 0; i < result.length; i++) {
        console.info(`Final result: ${JSON.stringify(result[i])}`);
      }
      callback(result);
    })
  }
}

let contactDataManager = new ContactDataManager();

export default contactDataManager;